//+------------------------------------------------------------------+
//|                                                          888.mq5 |
//|                                  Copyright 2025, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

// 输入参数
input int      EA_Magic = 5555;        // EA魔术棒
input int      BarsToAnalyze = 100;    // 分析的K线数量
input double   StepPoints = 500;       // 价位步长(点)
input int      MaxLevels = 10;         // 最大水平线数量

// 全局变量
datetime lastBarTime;                  // 记录最后处理的K线时间

//+------------------------------------------------------------------+
//| 初始化函数                                                       |
//+------------------------------------------------------------------+
int OnInit()
{
   lastBarTime = iTime(_Symbol, Period(), 0); // 初始化K线时间
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| 去初始化函数                                                     |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   // 删除所有魔术棒创建的对象
   ObjectsDeleteAll(0, IntegerToString(EA_Magic));
   Comment("");
}

//+------------------------------------------------------------------+
//| 价格分析结构体                                                   |
//+------------------------------------------------------------------+
struct SLevelInfo
{
   double price;
   int    count;
};

//+------------------------------------------------------------------+
//| Tick函数                                                         |
//+------------------------------------------------------------------+
void OnTick()
{
   // 检查新K线开始
   datetime currentBarTime = iTime(_Symbol, Period(), 0);
   if(lastBarTime != currentBarTime)
   {
      // 新K线开始，执行分析
      DoPriceAnalysis();
      lastBarTime = currentBarTime;
   }
}

//+------------------------------------------------------------------+
//| 执行价格分析并画线                                               |
//+------------------------------------------------------------------+
void DoPriceAnalysis()
{
   // 删除旧对象
   ObjectsDeleteAll(0, IntegerToString(EA_Magic));
   
   // 获取当前时间周期
   ENUM_TIMEFRAMES period = Period();
   
   // 确保有足够K线
   int totalBars = Bars(_Symbol, period);
   if(totalBars < BarsToAnalyze)
   {
      Comment("Not enough bars! Available: ", totalBars, " Need: ", BarsToAnalyze);
      return;
   }
   
   // 计算实际步长
   double step = StepPoints * _Point;
   if(step <= 0) step = 500 * _Point;
   
   // 获取价格范围
   double minPrice = DBL_MAX;
   double maxPrice = -DBL_MAX;
   for(int i = 0; i < BarsToAnalyze; i++)
   {
      minPrice = MathMin(minPrice, iLow(_Symbol, period, i));
      maxPrice = MathMax(maxPrice, iHigh(_Symbol, period, i));
   }
   
   // 计算区间数量
   int levelsCount = (int)MathCeil((maxPrice - minPrice) / step);
   if(levelsCount <= 0) return;
   
   // 初始化计数数组
   int count[];
   ArrayResize(count, levelsCount);
   ArrayInitialize(count, 0);
   
   // 统计价格分布
   for(int i = 0; i < BarsToAnalyze; i++)
   {
      double low = iLow(_Symbol, period, i);
      double high = iHigh(_Symbol, period, i);
      
      int startIdx = (int)MathFloor((low - minPrice) / step);
      int endIdx = (int)MathFloor((high - minPrice) / step);
      
      startIdx = MathMax(0, startIdx);
      endIdx = MathMin(levelsCount - 1, endIdx);
      
      if(startIdx > endIdx) continue;
      
      for(int j = startIdx; j <= endIdx; j++)
      {
         count[j]++;
      }
   }
   
   // 创建水平线数组
   SLevelInfo levels[];
   ArrayResize(levels, levelsCount);
   
   for(int i = 0; i < levelsCount; i++)
   {
      levels[i].price = minPrice + (i + 0.5) * step;
      levels[i].count = count[i];
   }
   
   // 自定义排序函数
   for(int i = 0; i < levelsCount - 1; i++)
   {
      for(int j = i + 1; j < levelsCount; j++)
      {
         if(levels[j].count > levels[i].count)
         {
            SLevelInfo temp = levels[i];
            levels[i] = levels[j];
            levels[j] = temp;
         }
      }
   }
   
   // 绘制水平线
   datetime endTime = iTime(_Symbol, period, 0);
   datetime startTime = iTime(_Symbol, period, BarsToAnalyze - 1);
   
   int levelsToDraw = MathMin(MaxLevels, levelsCount);
   
   // 准备显示穿透K线数量的字符串
   string countsStr = "Level Crossings: ";
   
   for(int i = 0; i < levelsToDraw; i++)
   {
      // 计算绿色深度（255到50线性递减）
      int greenValue = 255 - (i * 205 / (levelsToDraw > 1 ? levelsToDraw - 1 : 1));
      
      // 创建颜色 (使用十六进制表示法: 0xAAGGBBRR)
      color lineColor = 0xFF000000;  // 基础黑色
      lineColor += (greenValue << 8); // 添加绿色分量
      
      // 创建线段对象
      string name = StringFormat("%s_L%d", IntegerToString(EA_Magic), i);
      CreateTrendLine(name, startTime, levels[i].price, endTime, levels[i].price, lineColor);
      
      // 添加穿透数量到显示字符串
      countsStr += StringFormat("%d", levels[i].count);
      if(i < levelsToDraw - 1) countsStr += ", ";
   }
   
   // 显示穿透K线数量
   Comment(countsStr);
}

//+------------------------------------------------------------------+
//| 创建趋势线函数                                                   |
//+------------------------------------------------------------------+
void CreateTrendLine(string name, datetime t1, double p1, datetime t2, double p2, color clr)
{
   ObjectCreate(0, name, OBJ_TREND, 0, t1, p1, t2, p2);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, name, OBJPROP_WIDTH, 2);
   ObjectSetInteger(0, name, OBJPROP_RAY, false);
   ObjectSetInteger(0, name, OBJPROP_BACK, true);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
}
//+------------------------------------------------------------------+